<?php
class AlbumModel extends Model
{
    private $db;
    function  __construct()
    {
        $this->db = DataProvider::getInstance();
        parent::__construct();
    }

    public function getAlbumList()
    {
        $albums = $this->db->get('album')->getAll();
        foreach ($albums as &$album)
        {
            $rs = $this->db->get('item',array('album_id'=>$album->id), null, 1, 0);
            if (count($rs->getAll()) == 1)
                $album->thumbnail = $rs->getRow(0)->thumbnail;
        }
        return $albums;
    }

    public function getAlbum($id)
    {
        return $this->db->get('album', array('id'=>$id))->getRow(0);
    }

    public function getItem($id)
    {
        return $this->db->get('item', array('id'=>$id))->getRow(0);
    }

    public function getAlbumItems($id)
    {
        return $this->db->get('item', array('album_id'=>$id))->getAll();
    }

    public function addalbum($name, $description, $status)
    {
        if ($name == '') return " Hãy nhập tên album.";
        else
        {
            if ($status==2) $this->db->update('album',array('status'=>1), array('status'=>2));
            $albumInfo = array('name'=>$name, 'description'=>$description, 'status'=>$status);
            $this->db->insert('album', $albumInfo);
            $id = mysql_insert_id();
            if (!file_exists("../public/images/$id"))
            {
                mkdir("../public/images/$id", null, true);
                chmod("../public/images/$id",0777);
            }
            return null;
        }
    }

    public function updateAlbum($id, $name, $description, $status)
    {
        if ($name == '') return " Hãy nhập tên album.";
        else
        {
            if ($status==2) $this->db->update('album',array('status'=>1), array('status'=>2));
            $albumInfo = array('name'=>$name, 'description'=>$description, 'status'=>$status);
            $condition = array('id'=>$id);
            $this->db->update('album', $albumInfo, $condition);
            return null;
        }
    }

    public function addItem($description, $file, $link, $albumID)
    {
        $message = '';
        $maxSize = 2097152;
        $regex = "/^.*\.(jpg|jpeg|png|gif)$/i";

                if(!preg_match($regex, $file['name']))
                {
                    $message .= ' - Chỉ được upload ảnh với các định dạnh sau: png, jpg, jpeg, gif<br />';
                }
                if($file['size'] > $maxSize)
                {
                    $message .= " - Chỉ được upload ảnh kích thước tối đa là ". ($maxSize/1024) ." KB<br />";
                }
        
        if ($message != '') return $message;

        $rs = $this->db->query("SELECT Auto_increment FROM information_schema.tables WHERE table_name='item'");
        while ($r = mysql_fetch_array($rs))
            $id = $r['Auto_increment'];
        $arr = str_split($file['type'], 6);
        $ext = $arr[1];
        $thumbnail = "$albumID/$id-thumbnail.$ext";
        $image = "$albumID/$id-image.$ext";

        if (move_uploaded_file($file['tmp_name'], "../public/images/$albumID/$id-image.$ext"))
        {
            $this->make_thumb("../public/images/$albumID/$id-image.$ext", "../public/images/$albumID/$id-thumbnail.$ext", 85, 70);
            $itemData = array('description'=>$description, 'thumbnail'=>$thumbnail, 'image'=>$image, 'link'=>$link, 'album_id'=>$albumID);
            $this->db->insert('item', $itemData);
            return null;
        }
        else return "Có lỗi xảy ra trong quá trình upload file.";
    }

    public function updateItem($description, $link, $id)
    {
        $this->db->update('item', array('description'=>$description, 'link'=>$link), array('id'=>$id));
    }

    public function deleteAlbum($id)
    {
        $this->db->remove('item', array('album_id'=>$id));
        $this->db->remove('album', array('id'=>$id));
        $this->recursive_remove_directory("../public/images/$id");
    }

    public function deleteItem($id)
    {
        $item = $this->db->get('item', array('id'=>$id))->getRow(0);
        $this->db->remove('item', array('id'=>$id));
        if (file_exists("../public/images/$item->thumbnail")) unlink("../public/images/$item->thumbnail");
        if (file_exists("../public/images/$item->image")) unlink("../public/images/$item->image");
    }

    private function make_thumb($img_name,$filename,$new_w,$new_h)
    {
        //get image extension.
        $ext= $this->getExtension($img_name);
        //creates the new image using the appropriate function from gd library
        if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
            $src_img=imagecreatefromjpeg($img_name);

        if(!strcmp("png",$ext))
            $src_img=imagecreatefrompng($img_name);

        if (!isset($src_img)) return;
        //gets the dimmensions of the image
        $old_x=imageSX($src_img);
        $old_y=imageSY($src_img);

        // next we will calculate the new dimmensions for the thumbnail image
        // the next steps will be taken:
        // 1. calculate the ratio by dividing the old dimmensions with the new ones
        // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
        // and the height will be calculated so the image ratio will not change
        // 3. otherwise we will use the height ratio for the image
        // as a result, only one of the dimmensions will be from the fixed ones
        $ratio1=$old_x/$new_w;
        $ratio2=$old_y/$new_h;
        if($ratio1>$ratio2) {
            $thumb_w=$new_w;
            $thumb_h=$old_y/$ratio1;
        }
        else {
            $thumb_h=$new_h;
            $thumb_w=$old_x/$ratio2;
        }

        // we create a new image with the new dimmensions
        $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

        // resize the big image to the new created one
        imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

        // output the created image to the file. Now we will have the thumbnail into the file named by $filename
        if(!strcmp("png",$ext))
            imagepng($dst_img,$filename);
        else
            imagejpeg($dst_img,$filename);

        //destroys source and destination images.
        imagedestroy($dst_img);
        imagedestroy($src_img);
    }

    // This function reads the extension of the file.
    // It is used to determine if the file is an image by checking the extension.
    private function getExtension($str) {
        $i = strrpos($str,".");
        if (!$i) { return ""; }
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext;
    }

    private function recursive_remove_directory($directory, $empty=FALSE)
    {
         if(substr($directory,-1) == '/')
         {
             $directory = substr($directory,0,-1);
         }
         if(!file_exists($directory) || !is_dir($directory))
         {
             return FALSE;
         }elseif(is_readable($directory))
         {
             $handle = opendir($directory);
             while (FALSE !== ($item = readdir($handle)))
             {
                 if($item != '.' && $item != '..')
                 {
                     $path = $directory.'/'.$item;
                     if(is_dir($path))
                     {
                         recursive_remove_directory($path);
                     }else{
                         unlink($path);
                     }
                 }
             }
             closedir($handle);
             if($empty == FALSE)
            {
                 if(!rmdir($directory))
                 {
                     return FALSE;
                 }
             }
         }
         return TRUE;
    }

}